package com.ohs.ohsoa.system.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.ohs.ohsoa.system.dto.PasswordDto;
import com.ohs.ohsoa.system.entity.*;
import com.ohs.ohsoa.system.mapper.RouterMapper;
import com.ohs.ohsoa.system.mapper.UserInfoMapper;
import com.ohs.ohsoa.system.vo.*;
import com.ohs.ohsoa.utils.IsNull;
import com.ohs.ohsoa.utils.Md5Util;
import com.ohs.ohsoa.utils.auth.TokenService;
import com.ohs.ohsoa.utils.auth.TokenUtil;
import com.ohs.ohsoa.utils.bean.requestBean.PageParam;
import com.ohs.ohsoa.utils.exception.BizException;
import org.springframework.beans.BeanUtils;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 用户service实现类
 *
 * @author mwx
 * @since  2021年9月16日
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

	@Resource
	private UserInfoMapper userInfoMapper;

	@Resource
	private TokenService tokenService;

	@Resource
	private MessageSource messageSource;

	@Resource
	private RoleService roleService;

	@Resource
	private DepartmentService departmentService;

	@Resource
	private RouterMapper routerMapper;

	/**
	 * 根据name查询用户信息
	 *
	 * @param userName pwd 用户信息
	 * @return userinfo
	 * @author mwx
	 * @since  2021年10月08日
	 */
	@Override
	public LoginInfoVo login(String userName, String pwd) {
		UserInfo userInfo = userInfoMapper.getUserByNo(userName);
		if (IsNull.isNull(userInfo) || IsNull.isNull(userInfo.getPwd())) {
			throw new BizException("E0008", messageSource.getMessage("E0008", null, null));
		}
		if (!Md5Util.string2MD5(pwd).toUpperCase().equalsIgnoreCase(userInfo.getPwd())&&!pwd.equalsIgnoreCase(userInfo.getPwd())) {
				throw new BizException("E0009", messageSource.getMessage("E0009", null, null));
		}
		String token = tokenService.getToken(userInfo);
		LoginInfoVo loginInfoVo = new LoginInfoVo();
		loginInfoVo.setToken(token);
		loginInfoVo.setUserInfo(userInfo);

		// 登录用户 页面（权限）
		List<Router> routers = routerMapper.getUserRouter(userInfo.getRoleGuid());

		List<Router> pRouters = routerMapper.getPRouter(userInfo.getRoleGuid());

		List<RouterVo> routerVos = new ArrayList<>();
		for (Router prouter : pRouters) {

			RouterVo routerVo = new RouterVo();
			BeanUtils.copyProperties(prouter, routerVo);
			routerVo.setChildren(routers.stream().filter(item -> item.getPguid().equals(prouter.getRouterGuid()))
					.collect(Collectors.toList()));
			routerVos.add(routerVo);
		}

		loginInfoVo.setRouters(routerVos);
		return loginInfoVo;
	}

	/**
	 * 获取当前登录用户对象方法
	 *
	 * @return userinfo
	 * @author mwx
	 * @since  2021年10月08日
	 */
	@Override
	public UserInfoVo getUserInfo() {
		String userinfoGuid = TokenUtil.getTokenUserId();
		if(userinfoGuid != null) {
			return userInfoMapper.getUserById(userinfoGuid);
		}else {
			return null;
		}
	}

	/**
	 * 分页查询
	 *
	 * @param pageParam 减速用参数
	 * @return listUser
	 * @author mwx
	 * @since  2021年9月16日
	 */
	@Override
	public List<UserInfoVo> listUserInfo(PageParam<UserInfo> pageParam) {
		// 获取user对象
		UserInfo user = pageParam.getSearchbean();
		// 分页
		PageHelper.startPage(pageParam.getIndexPage(), pageParam.getPageSize());
		// 获取并返回user集合
		return  userInfoMapper.listUserInfo(user);
	}

	/**
	 * 查看详情
	 *
	 * @param userinfoGuid "实例对象"
	 * @return 1为成功
	 * @author mwx
	 * @since  2021年10月08日
	 */
	@Override
	public UserInfoVo getUserById(String userinfoGuid) {
		return userInfoMapper.getUserById(userinfoGuid);
	}

	/**
	 * 新增
	 *
	 * @param userInfo "实例对象"
	 * @return 1为成功
	 * @author mwx
	 * @since  2021年10月08日
	 */
	@Override
	public Boolean insert(UserInfo userInfo) {

		QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("user_no", userInfo.getUserNo());
		if (this.count(queryWrapper) > 0) {
			throw new BizException("E00010", messageSource.getMessage("E00010", null, null));
		}
		String id = UUID.randomUUID().toString().replace("-", "");
		userInfo.setUserinfoGuid(id);
		userInfo.setPwd(Md5Util.string2MD5(userInfo.getPwd()).toUpperCase());

		return userInfoMapper.insertUser(userInfo);
	}

	/**
	 * 修改
	 *
	 * @param userInfo"实例对象"
	 * @return 1为成功
	 * @author mwx
	 * @since  2021年10月12日
	 */
	@Override
	public Boolean update(UserInfo userInfo) {
		QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("user_no", userInfo.getUserNo()).ne("userinfo_guid", userInfo.getUserinfoGuid());
		if (this.count(queryWrapper) > 0) {
			throw new BizException("E00010", messageSource.getMessage("E00010", null, null));
		}
		if (userInfo.getPwd() != null) {
			userInfo.setPwd(Md5Util.string2MD5(userInfo.getPwd()).toUpperCase());
		}

		return userInfoMapper.updateUser(userInfo);
	}

	/**
	 * 批量删除数据
	 *
	 * @param ids "listId"
	 * @return 1为成功
	 * @author mwx
	 * @since  2021年10月12日
	 */
	@Override
	public Boolean deleteUserInfoById(List<String> ids) {
		return userInfoMapper.deleteUserInfoById(ids);
	}

	@Override
	public Boolean resetpassword(UserInfo userInfo) {
		UpdateWrapper<UserInfo> updateWrapper = new UpdateWrapper<>();
		// 初始密码 111111
		updateWrapper.in("userinfo_guid", userInfo.getIds()).set("pwd", "96E79218965EB72C92A549DD5A330112");
		return this.update(updateWrapper);
	}

	@Override
	public DepartmentAndRoleVo departmentAndRoleByEnterprises() {
		DepartmentAndRoleVo departmentAndRoleVo = new DepartmentAndRoleVo();
		List<GroupEnterpriseVo> groupEnterpriseVos = new ArrayList<>();

		List<GroupEnterprise> groupEnterprises = roleService.selectAllEnterprise();
		QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
		departmentQueryWrapper.eq("delete_flag", "1");
		List<Department> departments = departmentService.list(departmentQueryWrapper);
		QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
		roleQueryWrapper.eq("delete_flag", "1");
		List<Role> roles = roleService.list(roleQueryWrapper);
		if (groupEnterprises != null && groupEnterprises.size() > 0) {
			for (GroupEnterprise groupEnterprise : groupEnterprises) {
				GroupEnterpriseVo groupEnterpriseVo = new GroupEnterpriseVo();
				BeanUtils.copyProperties(groupEnterprise, groupEnterpriseVo);
				groupEnterpriseVo.setDepartments(departments.stream()
						.filter(item -> item.getGroupEnterpriseGuid().equals(groupEnterprise.getGroupEnterpriseGuid()))
						.collect(Collectors.toList()));
				groupEnterpriseVo.setRoles(roles.stream()
						.filter(item -> item.getGroupEnterpriseGuid().equals(groupEnterprise.getGroupEnterpriseGuid()))
						.collect(Collectors.toList()));
				groupEnterpriseVos.add(groupEnterpriseVo);
			}
			departmentAndRoleVo.setGroupEnterpriseVos(groupEnterpriseVos);
		}
		// 查询所有学历
		departmentAndRoleVo.setEducations(userInfoMapper.geteducationsList());
		return departmentAndRoleVo;
	}

//	@Override
//	public Boolean selectAuthority(UserInfo userInfo) {
//		return null;
//	}

	//	@Override
//	public Boolean selectAuthority(UserInfo userInfo) {
//		UpdateWrapper<UserInfo> updateWrapper = new UpdateWrapper<>();
//		updateWrapper.eq("userinfo_guid", userInfo.getUserinfoGuid()).set("authority", userInfo.getAuthority());
//		return this.update(updateWrapper);
//	}

	@Override
	public Boolean updatePassword(PasswordDto passwordDto) {
		UserInfoVo userInfoVo = this.getUserById(passwordDto.getUserinfoGuid());
		UserInfo userInfo = new UserInfo();
		BeanUtils.copyProperties(userInfoVo, userInfo);
		String password = Md5Util.string2MD5(passwordDto.getOldPassword()).toUpperCase();
		if (userInfo.getPwd().equals(password)) {
			userInfo.setPwd(passwordDto.getNewPassword());
			return this.update(userInfo);
		} else {
			throw new BizException("E00011", messageSource.getMessage("E00011", null, null));
		}
	}


}
